<?php
if (!defined('BASEPATH')) exit('No direct script access allowed');

class Users_mod extends CI_Model
{
    private $_emailConfig;
    private $_dbTableUsers = 'users';
    private $_dbTableLogOnline = 'log_online';
    private $_dbTableFriends = 'friends';
    private $_dbTableProfileViews = 'profile_views';
    private $_dbTableImages = 'images';
    private $_dbTablePromoCodes = 'promo_codes';
    private $_dbTableSpotlight = 'spotlight';
   
    /**
     *  class sonstructor
     */
    function __construct() 
	{
		// Call the Model constructor
        parent::__construct();
        
        $this->load->library('email');
  
        // define terms for emails
		$this->_emailConfig['mailtype'] = 'txt';
        $this->_emailConfig['useragent'] = 'PHP CodeIgniter';                
	}
    
    /**
     *  AJAX function LOGIN
     * 
     */ 
    public function login($login)
    {
        if(    isset($login['username']) && ""!=$login['username'] 
            && isset($login['password']) && ""!=$login['password']  )
        {
            $query = $this->db->select(' id, username, name, user_group ')
                              ->where('username',$login['username'])
                              ->where('password',md5($login['password']))
                              ->where('status',1) // Izvrsio je konfirmaciju
                              ->get($this->_dbTableUsers);
            $errors = $this->db->_error_message();
            if (!empty($errors)) {
              throw new Exception("SQL Error: " . $errors);
            } else { }
            
            if( $query->num_rows() == 1 ) // Podaci tacni
            {
              $user = $query->row();
              $query->free_result();
              
              $this->load->model('images_mod');
              $main_image = $this->images_mod->getMainImage($user->id);
              
              $this->session->set_userdata('user_logged',true);
              $this->session->set_userdata('user_id',$user->id);
              $this->session->set_userdata('username',$user->username);
              $this->session->set_userdata('name',$user->name);
              $this->session->set_userdata('main_img',$main_image);
              
              if( isset($login['remember']) && 1 == $login['remember'])
              {
                $this->load->helper('cookie');
                set_cookie('user_loged',true);
                set_cookie('user_id',$user->id);
                set_cookie('username',$user->username);
                set_cookie('name',$user->name);
                set_cookie('main_img',$main_image);
              }
              
              if( $user->user_group == 1 ) // user admin
              {
                $this->session->set_userdata('admin_logged',true);
				$this->session->set_userdata('admin_username',$user->username);
                $this->session->set_userdata('admin_id',$user->id);
              }
              
              $this->_setUserOnline($user->id);
              
              $response = true;
            }
            else
              $response = false;
        }
        else
        {
            $response = false;
        }
        return $response;
    }
   
    public function logout()
    {
        $user_id = $this->session->userdata('user_id');
        
        $this->db->where('user_id',$user_id)->delete($this->_dbTableLogOnline);
        
        $errors = $this->db->_error_message();
        if (!empty($errors)) {
          throw new Exception("SQL Error: " . $errors);
        } else { }
        
        $this->session->sess_destroy();
        
        $this->load->helper('cookie');
        delete_cookie('user_loged');
        delete_cookie('user_id');
        delete_cookie('username');
        delete_cookie('name');
        
        return true;
    }
    
    /**
     * PRONALAZENJE KORISNIKA
     * @param array $filter 
     */
    public function getSearchUsers($filter=NULL)
    {
        $this->db->distinct();
        $this->db->select("
                            {$this->_dbTableUsers}.`id`,
                            {$this->_dbTableUsers}.`username`,
                            {$this->_dbTableUsers}.`name`,
                            (YEAR(CURRENT_TIMESTAMP ) - YEAR( {$this->_dbTableUsers}.`birthdate` ) ) AS age,
                            (SELECT name FROM {$this->_dbTableImages} WHERE {$this->_dbTableImages}.user_id  = {$this->_dbTableUsers}.id AND main = 1 ORDER BY main desc LIMIT 1  ) as image_name
                           ");
        //$this->db->from($this->_dbTableUsers);
        $this->db->from($this->_dbTableUsers);
        if( ""!=$this->session->userdata('user_id') )
        {
          $this->db->where('id <>',$this->session->userdata('user_id')); // Ne prikazuj trenutno ulogovanog u rezlutatitma
        }
        $this->db->where('status',1); // Izvrsio je konfirmaciju 
        
        if( isset($filter['name']) && $filter['name']!="" )
        {
          //$this->db->like('name',$filter['name']);
          //$this->db->or_like('username',$filter['name']);
          $this->db->like('username',$filter['name']);
        }
        
        if( isset($filter['look_for']) && $filter['look_for']!="" && $filter['look_for']!='both')
        {
            $this->db->where('gender',$filter['look_for']);
        }
        
//        if( isset($filter['location']) && $filter['location']!="" )
//          $this->db->where('location',$filter['location']);
        if( isset($filter['postal_code']) && $filter['postal_code']!="" )
        {
          $this->db->like('zip_code',$filter['postal_code'],'after');
        }
        
        if( isset($filter['status_line']) && $filter['status_line']!="" )
        {
          if( $filter['status_line']=='online' )
          {           
            $this->db->where("{$this->_dbTableUsers}.id IN (SELECT user_id FROM `{$this->_dbTableLogOnline}`) ");
          }
          else // offline
          {            
            $this->db->where("{$this->_dbTableUsers}.id NOT IN (SELECT user_id FROM `{$this->_dbTableLogOnline}`) ");           
          }
        }
        
        if( isset($filter['year_from']) && $filter['year_from']!="" )
          $this->db->where('(YEAR(CURRENT_TIMESTAMP ) - YEAR( users.`birthdate` ))>=',$filter['year_from']);
        
        if( isset($filter['year_to']) && $filter['year_to']!="" )
          $this->db->where('(YEAR(CURRENT_TIMESTAMP ) - YEAR( users.`birthdate` )) <=',$filter['year_to']);
        
        // Samo korisnici koji su obicni useri mogu da se prikazuju
        $this->db->where('user_group',3); // user_group = { 1=admin, 2=moderator, 3=user }
        
        $query = $this->db->get();
        //echo $this->db->last_query();
        $errors = $this->db->_error_message();
        if (!empty($errors)) {
          throw new Exception("SQL Error: " . $errors);
        } else { }

        if ($query->num_rows() > 0) {
          
          $users = $query->result(); // 
          $query->free_result();
        } else {
          $users = NULL;
        }

        return $users;
        
    }
    
    public function getNumOnline()
    {
        $sess_id = $this->session->userdata('session_id');
        $ip = $this->ipCheck();
        if(  $this->session->userdata('user_id')  )
          $user_id = $this->session->userdata('user_id');
        else
          $user_id = 0;
        $refresh_time = $this->config->item('refresh_time');
        
        $time = time();        
        $date_time = date("Y-m-d H:i:s",$time);
        $select_time = date("Y-m-d H:i:s",$time - $refresh_time);
        $delete_time = date("Y-m-d H:i:s",$time - 2*$refresh_time);
        
        $ip = $this->ipCheck();
        $query = $this->db->select('user_id')
                          ->from($this->_dbTableLogOnline)
                          //->where('session_id',$sess_id)
                          ->where('user_id',$user_id)
                          ->get();
        if( $query->num_rows()>0 )
        {
          $this->db->where('user_id',$user_id)
                   ->update($this->_dbTableLogOnline,array('time'=>$date_time /*, 'session_id'=>$sess_id */ ));
          //echo $this->db->last_query();
        }
        else if( 0 != $user_id )
        {
          $this->db->insert($this->_dbTableLogOnline,
                            array(
                                //'session_id'=>$sess_id,
                                'ip' => $ip,
                                'user_id' => $user_id,
                                'time' => $date_time
                            )
                           );
          //echo $this->db->last_query();
        }
        
        $this->db->query(" DELETE FROM {$this->_dbTableLogOnline} WHERE '{$delete_time}' > `time`; ");
        
       $query = $this->db->query("SELECT DISTINCT {$this->_dbTableLogOnline}.`user_id` FROM {$this->_dbTableLogOnline},{$this->_dbTableUsers} WHERE {$this->_dbTableLogOnline}.`user_id` = {$this->_dbTableUsers}.`id` AND {$this->_dbTableUsers}.`user_group`=3 AND `time` > '{$select_time}'");
        
        return $query->num_rows();
    }
    
        
    public function isAdminOnline()
    {
      $query = $this->db->select($this->_dbTableUsers.".id")
                        ->from($this->_dbTableLogOnline)
                        ->join($this->_dbTableUsers,"{$this->_dbTableUsers}.id = {$this->_dbTableLogOnline}.user_id")
                        ->where($this->_dbTableUsers.".user_group",1) // Admin
                        ->get();
      $errors = $this->db->_error_message();
      if (!empty($errors)) {
        throw new Exception("SQL Error: " . $errors);
      } else { }
      
      if( $query->num_rows() > 0 )
      {
        $result = true;
        $query->free_result();
      }
      else
      {
        $result = false;
      }
      
      return $result;
    }
    
    public function getUserData($id,$like_array = true)
    {
      $this->db->select('*');
      
      $this->db->where('id',$id);
      
      $query = $this->db->get($this->_dbTableUsers);                         
                        
      //echo $this->db->last_query();
      $errors = $this->db->_error_message();
      if (!empty($errors)) {
        throw new Exception("SQL Error: " . $errors);
      } else { }

      if ($query->num_rows() == 1) {
        if($like_array) 
        {
          $user = $query->row_array(); // Return ONE ROW ARRAY
          $user['age'] = date("Y") - ceil( substr($user['birthdate'], 0, 4) );
          $user['is_online'] = $this->_isOnline($user['id']);
          $user['is_my_friend'] = $this->isMyFriend($user['id']);
          $user['have_promo_code'] = $this->getPromoCode($user['id']);
        }
        else
        {
          $user = $query->row(); // RETRURN ONE ROW 
          $user->age = date("Y") - ceil( substr($user->birthdate, 0, 4) );
          $user->is_online = $this->_isOnline($user->id);
          $user->is_my_friend = $this->isMyFriend($user->id);
          $user->have_promo_code = $this->getPromoCode($user->id);
        }
        
        $query->free_result();
      } else {
        $user = NULL;
      }
       
      return $user;
    }
    
    
    public function getPromoCode($id)
    {
      $query = $this->db->select('id')
                        ->from($this->_dbTablePromoCodes)
                        ->where($this->_dbTablePromoCodes.".user_id",$id)
                        ->where('is_used',0) // nije iskoriscen
                        ->get();
      //echo $this->db->last_query();
      $errors = $this->db->_error_message();
      if (!empty($errors)) {
        throw new Exception("SQL Error: " . $errors);
      } else { }
      
      if ($query->num_rows() == 1) {
        $result = true;//$query->row()->id;
        $query->free_result();
      } else {
        $result = false;
      }

      return $result;      
    }
    
    public function getUserDataByUsername($username,$like_array = true)
    {
      $this->db->select('*');
      
      $this->db->where('username',$username);
      
      $query = $this->db->get($this->_dbTableUsers);                         
                        
      //echo $this->db->last_query();
      $errors = $this->db->_error_message();
      if (!empty($errors)) {
        throw new Exception("SQL Error: " . $errors);
      } else { }

      if ($query->num_rows() >= 1) {
        if($like_array) 
        {
          $user = $query->row_array(); // Return ONE ROW ARRAY
          $user['age'] = date("Y") - ceil( substr($user['birthdate'], 0, 4) );
          $user['is_online'] = $this->_isOnline($user['id']);
          $user['is_my_friend'] = $this->isMyFriend($user['id']);
        }
        else
        {
          $user = $query->row(); // RETRURN ONE ROW 
          $user->age = date("Y") - ceil( substr($user->birthdate, 0, 4) );
          $user->is_online = $this->_isOnline($user->id);
          $user->is_my_friend = $this->isMyFriend($user->id);
        }
        
        $query->free_result();
      } else {
        $user = NULL;
      }
      
      return $user;
    }
    
    
    public function setViewProfile( $my_id, $user_id )
    {
      $data = array( 
                      'my_id' => $my_id, 
                      'user_id' => $user_id
                   );
      $this->db->insert($this->_dbTableProfileViews,$data);
      
      $errors = $this->db->_error_message();
      if (!empty($errors)) {
        throw new Exception("SQL Error: " . $errors);
      } else { }
      
    }
    
    
    public function getNumViewMyProfile()
    {
      $num_days = $this->config->item('num_last_days_who_viewed_profile');
      $id = $this->session->userdata('user_id');
      $query = $this->db//->distinct()
                        ->select('my_id')
                        ->from($this->_dbTableProfileViews)
                        ->where($this->_dbTableProfileViews.".user_id",$id)
                        ->where($this->_dbTableProfileViews.".timestamp > DATE_SUB(NOW(), INTERVAL {$num_days} DAY) ")
                        ->get();
      //echo $this->db->last_query();
      $errors = $this->db->_error_message();
      if (!empty($errors)) {
        throw new Exception("SQL Error: " . $errors);
      } else { }
      
      $result = $query->num_rows();
      $query->free_result();
     
      return $result;
    }
    
    public function getWhosViewedMyProfile()
    {
      $num_days = $this->config->item('num_last_days_who_viewed_profile');
      $id = $this->session->userdata('user_id');
            
        $this->db->select("
                          {$this->_dbTableUsers}.`id`,
                          {$this->_dbTableUsers}.`username`,
                          {$this->_dbTableUsers}.`name`,
                          ( SELECT name FROM {$this->_dbTableImages} WHERE {$this->_dbTableImages}.user_id = {$this->_dbTableUsers}.`id` AND main = 1 ORDER BY main asc LIMIT 1 ) as image_name,
                          ( SELECT COUNT(*) FROM {$this->_dbTableProfileViews} WHERE my_id = {$this->_dbTableUsers}.id AND user_id = $id ) as num_view 
                          ");
        $this->db->from($this->_dbTableUsers);
        $this->db->where("{$this->_dbTableUsers}.id IN (SELECT my_id FROM `{$this->_dbTableProfileViews}` WHERE   user_id = $id ) ");  
        //$this->db->join( $this->_dbTableProfileViews, "{$this->_dbTableProfileViews}.user_id = {$this->_dbTableUsers}.id");
        
        //$this->db->where('status',1); // Izvrsio je konfirmaciju 
        //$this->db->where('user_group',3); // user_group = { 1=admin, 2=moderator, 3=user }
        
        $query = $this->db->get();
        //echo $this->db->last_query();
        $errors = $this->db->_error_message();
        if (!empty($errors)) {
          throw new Exception("SQL Error: " . $errors);
        } else { }

        if ($query->num_rows() > 0) {
// Placanje za gledanje spiska ko je gledao moj profil
          //if( true == $this->_payWhyViewed() )
            $users = $query->result(); // 
          //else
          //  $users = NULL;
          
          $query->free_result();
        } else {
          $users = NULL;
        }

        return $users;
    }
    
    
    private function _payWhyViewed()
    {
        $id = $this->session->userdata('user_id');
//        if( true ==  $this->session->userdata('is_pay_who_viewed_profile') )
//          return true;
        $coins = $this->_getUserCoins();
        
        $viewed_cost = $this->config->item('who_viewed_profile_cost');
        if( $coins >= $viewed_cost )
        {
          // Smanji kredit 
          $sql = "UPDATE {$this->_dbTableUsers} SET `coins`=`coins`-{$viewed_cost} WHERE `id`={$id}; ";
          $query = $this->db->query($sql);
          
          $errors = $this->db->_error_message();
          if (!empty($errors)) {
            throw new Exception("SQL Error: " . $errors);
          } else { }
          
          if ($this->db->affected_rows() == 1) {
              $this->session->set_userdata('is_pay_who_viewed_profile',true);
              return true;
              //$query->free_result();
          } else { 
            return false;
          }
        }
        else
          return false;
    }
    
    
    private function _isOnline($user_id)
    {
      $refresh_time = $this->config->item('refresh_time');
      $time = date("Y-m-d H:i:s",time()-$refresh_time/2);
      $query = $this->db->select('user_id')
                        ->from($this->_dbTableLogOnline)
                        ->where('user_id',$user_id)
                        //->where('time >',$time)
                        ->get();
      $errors = $this->db->_error_message();
      if (!empty($errors)) {
        throw new Exception("SQL Error: " . $errors);
      } else { }
      
      if( $query->num_rows() > 0 )
      {
        $result = true;
        $query->free_result();
      }
      else
      {
        $result = false;
      }
      
      return $result;
    }
    
    
    public function forgot_password($email)
    {
         $query = $this->db->select(' id, username, email ')
                           ->where('email',$email)                           
                           ->get($this->_dbTableUsers);
         $errors = $this->db->_error_message();
         if (!empty($errors)) {
           throw new Exception("SQL Error: " . $errors);
         } else { }

         if( $query->num_rows() == 1 ) // Podaci tacni
         {
           $user = $query->row();
           $query->free_result();
           
           $time = date("Y-m-d H:i:s",time());
           $this->load->helper('string');
           $new_password = random_string('alnum', 8);
           $data = array('password' => md5($new_password) );
           $this->db->where('id',$user->id)->update($this->_dbTableUsers,$data);   
           
           $message = lang('forgot_password_message_text').": '".$new_password."'
            
Message time: {$time}
  
Your flitreoo.es
            
";
           $this->email->clear();
           $this->email->initialize($this->_emailConfig);

           $this->email->to($user->email);
           
           $this->email->from($this->config->item('mail_from'));
           $this->email->subject(lang('forgot_password'));
           $this->email->message($message);

           if (!$this->email->send()) {
              // Generate error (by CI)
              throw new Exception("Email cannot be sent. Try again or contact admin!");
              //echo $this->email->print_debugger();
              return false;
           }          

           return true;
         }
         else {
           return false;
         }
    }
    
    /**
     * F-ja koja proverava da li postoji user sa korisnickim imenom $username
     * @param string $username - korisnicko ime user-a
     * @return boolean true/false - posoji ili nepostoji user sa korisnickim iemenom $username
     * @throws Exception: SQL Errors
     */
    public function check_username($username)
    {
        $query = $this->db->select('id')->where('username',$username)->get($this->_dbTableUsers);
        
        $errors = $this->db->_error_message();
        if (!empty($errors)) {
          throw new Exception("SQL Error: " . $errors);
        } else { }

        if ($query->num_rows() > 0) {
          $result = true;
          $query->free_result();
        } else {
          $result = false;
        }

        return $result;
    }
    public function check_email($email,$id=NULL)
    {
        $this->db->select('id')
                 ->where('email',$email);
        if( $this->session->userdata('user_id') != NULL ) 
          $this->db->where('id <>'.$this->session->userdata('user_id'));
        
        // Za admina-a. On moze da menja podatke user-a
        if( $this->session->userdata('admin_logged') && $id != NULL ) 
          $this->db->where("id <>".$id);
        
        $query = $this->db->get($this->_dbTableUsers);
        
        //echo $this->db->last_query();
        $errors = $this->db->_error_message();
        if (!empty($errors)) {
          throw new Exception("SQL Error: " . $errors);
        } else { }

        if ($query->num_rows() > 0) {
          $result = true;
          $query->free_result();
        } else {
          $result = false;
        }

        return $result;
    }
    
    
    
    public function register($user)
    {
      
        if( $user['password'] != $user['repeat_password'] )
        {
          throw new Exception("Error: " . lang('password_does_not_match'));
          return;
        }
        $password = $user['password'];
        unset($user['repeat_password']);
        $user['password'] = md5($password);
        $user['registration_date'] = date("Y-m-d H:i:s",time());
        $user['birthdate'] = $user['birthdate']['year']."-".$user['birthdate']['month']."-".$user['birthdate']['day'];
        $user['ip_address'] = $this->ipCheck();
        //unset($user['birthdate']['year']);
        //unset($user['birthdate']['month']);
        //unset($user['birthdate']['day']);
        $this->db->insert($this->_dbTableUsers,$user);
        $id = $this->db->insert_id();
        $errors = $this->db->_error_message();
        if (!empty($errors)) {
          throw new Exception("SQL Error: " . $errors);
        } else { }
        
        $link = base_url()."register/confirm_registration.htm?a=".$id."&b=".md5($user['email']);
        
        // Send mail to user
        $message = lang('register_user_text')."
          

    ".lang('username').": ".$user['username']."
    ".lang('password').": ".$password."
      
    ".lang('confirm_text')."  
     
        {$link}
        

Message time: {$user['registration_date']}
  
Your flitreoo.es
            
";
           $this->email->clear();
           $this->email->initialize($this->_emailConfig);

           $this->email->to($user['email']);
           
           $this->email->from($this->config->item('mail_from'));
           $this->email->subject(lang('register')." - flirteoo.es");
           $this->email->message($message);

           if (!$this->email->send()) {
              // Generate error (by CI)
              throw new Exception("Email cannot be sent. Try again or contact admin!");
              //echo $this->email->print_debugger();
              return false;
           }
        
        return $id;
    }
    
    public function getRegisterUserData($id)
    {
        $query = $this->db->select('id,email,username,gender,look_for,birthdate,location,state,zip_code,flirt_text')
                          ->where('id',$id)
                          ->get($this->_dbTableUsers);
        $errors = $this->db->_error_message();
        if (!empty($errors)) {
          throw new Exception("SQL Error: " . $errors);
        } else { }

        if ($query->num_rows() == 1) {
          $result = $query->row();
          $query->free_result();
        } else {
          $result = NULL;
        }

        return $result;
    }
    
    public function userConfirmRegistration($id)
    {
        $data = array('status'=>1,'coins'=>$this->config->item('free_coins'));
        $this->db->where('id',$id)->update($this->_dbTableUsers,$data);
        $errors = $this->db->_error_message();
        if (!empty($errors)) {
          throw new Exception("SQL Error: " . $errors);
        } else { }
        
        // Kreiranje foldera za slike i kopiranje index.html file-a
        //Kreiranje big i small direktorijuma
        $base_dir = $this->config->item('image_path');
        @mkdir($base_dir.$id);
        
        $big = $base_dir.$id."/big"; // Za velike slike (max 1024x...)
        @mkdir($big);
        
        $small = $base_dir.$id."/small"; // Za male slicice (230x...)
        @mkdir($small); 
        
        $thumb = $base_dir.$id."/thumb"; // Za male slicice (100x100)
        @mkdir($thumb); 
        
        // Kopiranje index.html file-a
        $source = $base_dir."index.html";
        $dest = $base_dir.$id."/index.html";
        $dest1 = $big."/index.html";
        $dest2 = $small."/index.html";
        $dest3 = $thumb."/index.html";
        @copy($source, $dest);
        @copy($source, $dest1);
        @copy($source, $dest2);
        @copy($source, $dest3);
        
        return true;
    }
    
    
    
    
    
    public function saveUser($data)
    {
        // Ako je setovan password onda mora da bude jednak i sa ponovljenim passwordom
        if( $data['password']!="" )
        {
          if ( $data['password']!=$data['repeat_password'] ) 
            return false;
          else {
            $data['password'] = md5($data['password']);
          }
        }
        else {
          unset( $data['password'] );
        }
        
        unset( $data['repeat_password'] );
        
        $data['birthdate'] = $data['birthdate']['year']."-".$data['birthdate']['month']."-".$data['birthdate']['day'];
        $id = $data['id'];
        unset($data['id']);
        
        $this->db
               ->where('id',$id)
               ->update($this->_dbTableUsers,$data);
       //echo $this->db->last_query();
        $errors = $this->db->_error_message();
        if (!empty($errors)) {
          throw new Exception("SQL Error: " . $errors);
        } else { }
        
       return true;
    }
    
    public function editItem($field,$data)
    {
       $data = array( $field => $data  );
       $this->db
               ->where('id',$this->session->userdata('user_id'))
               ->update($this->_dbTableUsers,$data);
       //echo $this->db->last_query();
        $errors = $this->db->_error_message();
        if (!empty($errors)) {
          throw new Exception("SQL Error: " . $errors);
        } else { }
        
       return true;
    }
    
    private function _setUserOnline($user_id)
    {
        //$data['session_id'] = $this->session->userdata('session_id');
        $data['user_id'] = $user_id;
        $data['ip'] = $this->session->userdata('ip_address');
        
        $query = $this->db->insert($this->_dbTableLogOnline,$data);
        
        $errors = $this->db->_error_message();
        if (!empty($errors)) {
          throw new Exception("SQL Error: " . $errors);
        } else { }
        
        return true;
    }
    
    
    /*
	This function will try to find out if user is coming behind proxy server. Why is this important?
	If you have high traffic web site, it might happen that you receive lot of traffic
	from the same proxy server (like AOL). In that case, the script would count them all as 1 user.
	This function tryes to get real IP address.
	Note that getenv() function doesn't work when PHP is running as ISAPI module
	*/
    private function ipCheck() {
	
		if (getenv('HTTP_CLIENT_IP')) {
			$ip = getenv('HTTP_CLIENT_IP');
		}
		elseif (getenv('HTTP_X_FORWARDED_FOR')) {
			$ip = getenv('HTTP_X_FORWARDED_FOR');
		}
		elseif (getenv('HTTP_X_FORWARDED')) {
			$ip = getenv('HTTP_X_FORWARDED');
		}
		elseif (getenv('HTTP_FORWARDED_FOR')) {
			$ip = getenv('HTTP_FORWARDED_FOR');
		}
		elseif (getenv('HTTP_FORWARDED')) {
			$ip = getenv('HTTP_FORWARDED');
		}
		else {
			$ip = $_SERVER['REMOTE_ADDR'];
		}
		return $ip;
	}
     
    
    public function isMyFriend($friend_id)
    {
        $id = $this->session->userdata('user_id');
        $query = $this->db->select('id')
                          ->from($this->_dbTableFriends)
                          ->where('user_id',$id)
                          ->where('friend_id',$friend_id)
                          ->where('accept',1)
                          ->get();
        $errors = $this->db->_error_message();
        if (!empty($errors)) {
          throw new Exception("SQL Error: " . $errors);
        } else { }

        if ($query->num_rows() > 0) {
          $result = true;
          $query->free_result();
        } else {
          $result = false;
        }

        return $result;
    }
    public function updateCoins($coins, $user_id){
//        if( $coins > 0 )
//          $this->db->set("coins = `coins` + {$coins} ");
//        else
//        {
//          $coins = (-1)*$coins;
//          $this->db->set(" coins = `coins` - {$coins} ");
//        }        
//        $this->db->where('user_id',$user_id);
//        $this->db->update($this->_dbTableUsers);
        if( $coins > 0 )
        {
          $sql = "UPDATE {$this->_dbTableUsers} SET `coins` = `coins` + {$coins} WHERE `id` = $user_id; ";
        }
        else
        {
          $coins = (-1)*$coins;
          $sql = "UPDATE {$this->_dbTableUsers} SET `coins` = `coins` - {$coins} WHERE `id` = $user_id; ";
        }
        $this->db->query($sql);
        
        $errors = $this->db->_error_message();
        if (!empty($errors)) {
          throw new Exception("SQL Error: " . $errors);
          return false;
        } else {
            return true;
        }
    }
    
    private function _getUserCoins()
    {
        $id = $this->session->userdata('user_id');
//        if( true ==  $this->session->userdata('is_pay_who_viewed_profile') )
//          return true;
        $query = $this->db->select('coins')->from($this->_dbTableUsers)->where('id',$id)->get();
        
        $errors = $this->db->_error_message();
        if (!empty($errors)) {
          throw new Exception("SQL Error: " . $errors);
        } else { }
        
        if( $query->num_rows() == 1 )
        {          
          $coins=$query->row()->coins;
        }
        else
        {
          $coins = 0;
        }
        
        return $coins;
    }
    
    public function acceptPromoCode($id,$code)
    {
        $num_coins = $this->config->item('promotion_code');
        $sql = " UPDATE {$this->_dbTableUsers}, {$this->_dbTablePromoCodes} 
                 SET 
                      {$this->_dbTableUsers}.coins ={$this->_dbTableUsers}.coins+{$num_coins},
                      {$this->_dbTablePromoCodes}.is_used = 1
                 WHERE {$this->_dbTableUsers}.id = $id AND 
                       {$this->_dbTablePromoCodes}.user_id = $id AND 
                       {$this->_dbTablePromoCodes}.code = '$code' AND
                       {$this->_dbTablePromoCodes}.is_used = 0
                 ;
               ";
        $query = $this->db->query($sql);
        $errors = $this->db->_error_message();
        if (!empty($errors)) {
          throw new Exception("SQL Error: " . $errors);
          return false;
        } else { }
        
        if( $this->db->affected_rows()>0 ) {
          return true;
        }
        else {
          return false;
        }
    }
    
    public function addToSpotlight()
    {
      $id = $this->session->userdata('user_id');
      $num_days = $this->config->item('spotlight_days');
      $coins = $this->_getUserCoins();
      $spotlight_cost = $this->config->item('spotlight_cost');
      
      $query = $this->db->select('id')->from($this->_dbTableSpotlight)
                        ->where('user_id',$id)
                        ->where("added_date >= DATE_SUB( NOW(), INTERVAL {$num_days} DAY )")
                        ->get();
      // echo $this->db->last_query();
      $num_rows = $query->num_rows();
      if( $coins >= $spotlight_cost && $num_rows == 0 ) // Ima para i nije vec u spotlight
      {
        $data = array('user_id'=>$id);
        $this->db->insert($this->_dbTableSpotlight,$data); // Dodaj u spotlight
        $errors = $this->db->_error_message();
        if (!empty($errors)) {
          throw new Exception("SQL Error: " . $errors);
          return false;
        } else { }
        
        if(  $this->db->affected_rows()>0  ) // Ako je dodat u spotlight
        {
          // Naplati uslugu
          $spotlight_cost = (-1)*$spotlight_cost;
          $this->updateCoins($spotlight_cost, $id);
          return 1;
        }
      }
      else if(  $coins < $spotlight_cost )
        return -2;
      else if( $num_rows != 0  )
        return -3;
      else 
        return false;
    }
    /*
     SELECT name  FROM {$this->_dbTableImages} WHERE `private`=0 and {$this->_dbTableImages}.`user_id`= {$this->_dbTableMessages}.`from` ORDER BY main desc LIMIT 1
     */
    public function getSpotlightUsers()
    {
      //$id = $this->session->userdata('user_id');
      $num_days = $this->config->item('spotlight_days');
      
      $query = $this->db->select("
                                  {$this->_dbTableUsers}.id,
                                  {$this->_dbTableUsers}.username,
                                  {$this->_dbTableUsers}.name,
                                  ( SELECT name FROM {$this->_dbTableImages}  
                                                WHERE {$this->_dbTableImages}.`user_id` = {$this->_dbTableUsers}.`id`
                                                /*AND {$this->_dbTableImages}.main = 1 */
                                                ORDER BY main desc
                                                LIMIT 1
                                  ) as main_img
                                 ")
                        ->from($this->_dbTableUsers)
                        //->from($this->images)
                        ->join( $this->_dbTableSpotlight, "{$this->_dbTableSpotlight}.user_id = {$this->_dbTableUsers}.id" )
                        ->where("added_date >= DATE_SUB( NOW(), INTERVAL {$num_days} DAY )")
                        ->order_by('added_date','DESC')
                        ->get();
                        
      //echo $this->db->last_query();
      $errors = $this->db->_error_message();
      if (!empty($errors)) {
        throw new Exception("SQL Error: " . $errors);
      } else { }

      if ($query->num_rows() > 0) {
        $result = $query->result();
        $query->free_result();
      } else {
        $result = NULL;
      }

      return $result;
                                                        
    }
   
} // end class Users_mod

/*
      $query = $this->db->select('*')
                        ->from()
                        ->where()
                        ->get();
      //echo $this->db->last_query();
      $errors = $this->db->_error_message();
      if (!empty($errors)) {
        throw new Exception("SQL Error: " . $errors);
      } else { }

      if ($query->num_rows() > 0) {
        $result = $query->result();
        $query->free_result();
      } else {
        $result = NULL;
      }

      return $result;
 */

// end file: application/models/users_mod.php
?>
